package com.abing.api.utils;


import com.abing.api.model.NameValueField;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @Author CaptainBing
 * @Date 2024/8/24 20:57
 * @Description
 */
public class QueryStringUtils {

    private QueryStringUtils(){}

    public static String buildQueryString(String url, Map<String, NameValueField> paramMap){

        boolean containsQuestionMark = url.contains("?");

        StringBuilder queryString = new StringBuilder();

        boolean isFirst = true;
        for (Map.Entry<String, NameValueField> entry : paramMap.entrySet()) {
            try {
                NameValueField nameValueField = entry.getValue();
                String key = URLEncoder.encode(nameValueField.getName(), "UTF-8");
                String value = URLEncoder.encode(nameValueField.getValue(), "UTF-8");

                if (!isFirst) {
                    queryString.append("&");
                }
                queryString.append(key).append("=").append(value);
                isFirst = false;
            } catch (UnsupportedEncodingException e) {
                // UTF-8编码是Java平台的标准字符集，因此这里捕获异常主要是为了日志记录或抛出更具体的异常  
                throw new RuntimeException("Unsupported encoding UTF-8", e);
            }
        }

        return containsQuestionMark
                ? url + "&" + queryString
                : url + "?" + queryString;

    }

}
